from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth

# Create your views here.


def not_login_redirect(url):
    '''not login redirect to url page use @not_login_redirect(url)'''
    def nologin(func):
        def warps(request):
            if not request.user.is_authenticated():
                return HttpResponseRedirect(url)
            return func(request)
        warps.__name__ = func.__name__
        return warps
    return nologin


@not_login_redirect('/status/')
def index(request):
    return render(request, 'index.html')
    #return  render_to_response('index.html')

def account_login(request):
    print request.POST
    username = request.POST.get('username')
    password=request.POST.get('password')
    user = auth.authenticate(username= username,password= password)
    if user is not None:
        auth.login(request,user)
        return HttpResponseRedirect('/status/')
    else:
    	return render(request,'index.html',{'login_err':"Wrong username and password"})

def status(request):
    return render(request,'status.html',{'user':request.user})

def logout(request):
    user = request.user
    auth.logout(request)

    return HttpResponse("<h3>user %s logout success!</h3>" % request.user)


